package com.cjy.attach;

import com.cjy.common.MD5Util;
import com.cjy.common.SHACoder;
import com.cjy.date.DateUtils;
import com.cjy.string.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @author Cheng JiYe
 * @description:
 * @date 2020/5/2012:44
 */
public class AttachSerUtils {
    /**
     * 附件文件上传
     *
     * @param request
     * @param request
     * @return
     * @throws Exception
     */
    public Map<String, Object> uploadFile(HttpServletRequest request) throws Exception {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String busType = request.getParameter("busType");
        String busId = request.getParameter("busId");
        long busIdL = 0;
        if (!StringUtils.isEmpty(busId)) {
            busIdL = Long.parseLong(busId);
        }
        //String rootPath = sysConfigService.getParamValue("ATTACH_ROOT_PATH");
        String rootPath = "ATTACH_ROOT_PATH";
        if (StringUtils.isEmpty(rootPath)) {
            resultMap.put("code", "1001");
            resultMap.put("msg", "服务器附件存储路径未配置!");
            return resultMap;
        }

        //当前日期(按月保存)
        String date = DateUtils.getDateToString(new Date(), "yyyyMM");
        String attachAddr = "/" + date; //增加当月目录
        String dirPath = rootPath + attachAddr;
        File f = new File(dirPath);
        if (!f.exists()) {
            f.mkdirs();
        }
        int cnt = 0;
        List<Long> attachIdList = new ArrayList<>();
        MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
        Iterator<String> fileNames = params.getFileNames();
        while (fileNames.hasNext()) {
            String fileName = fileNames.next();
            String attachFileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
            MultipartFile file = params.getFile(fileName);
            byte[] bytes = file.getBytes();
            //生成附件唯一标识
            String attachCode = MD5Util.getMD5(SHACoder.encodeSHA512Hex(bytes));
            //AttachFile attachFile = attachFileMapper.selectByPrimaryKey(attachCode);
            Object attachFile = new Object();
            if (attachFile != null) { //数据库已有文件记录，则不做文件添加和保存
                //System.out.println("文件已经存在 ");

            } else {
                String attachFileName = attachCode + "." + attachFileExt;
                // 保存的最终文件完整路径(使用文件唯一标识作为文件名)
                String fileAddr = attachAddr + "/" + attachFileName;
                BufferedOutputStream stream = null;
                try {
                    stream = new BufferedOutputStream(new FileOutputStream(new File(rootPath + fileAddr)));
                    stream.write(bytes);
                } catch (Exception e) {
                    throw e;
                } finally {
                    if (stream != null) {
                        stream.close();
                        stream = null;
                    }
                }
            }
            cnt++;
        }

        if (cnt > 0) {
            resultMap.put("code", "200");
            resultMap.put("msg", "文件上传成功!");
            resultMap.put("attachIdList", attachIdList);
            return resultMap;
        } else {
            //默认返回信息
            resultMap.put("code", "1001");
            resultMap.put("msg", "上传失败!");
            return resultMap;
        }
    }

    /**
     * 文件下载
     *
     * @param response
     */
    public void download(HttpServletResponse response) throws Exception {

        //String rootPath = sysConfigService.getParamValue("ATTACH_ROOT_PATH");
        //文件存储的根路径
        String rootPath = "ATTACH_ROOT_PATH";


        //String fileDownloadPath = rootPath + attachFile.getAttachAddr();
        String fileDownloadPath = rootPath + "attachAdd";
        // 文件地址，真实环境是存放在数据库中的
        File file = new File(fileDownloadPath);
        // 穿件输入对象
        FileInputStream fis = new FileInputStream(file);
        // 设置相关格式
        response.setContentType("application/force-download");
        // 设置下载后的文件名以及header
        //response.addHeader("Content-disposition", "attachment;fileName=" + attachInfo.getAttachName());
        response.addHeader("Content-disposition", "attachment;fileName=" + "attachName");
        // 创建输出对象
        OutputStream os = response.getOutputStream();
        // 常规操作
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        fis.close();
    }

    /**
     * 在线预览接口
     *
     * @param response
     */
    public void attachPreview(HttpServletResponse response) {

        //String rootPath = sysConfigService.getParamValue("ATTACH_ROOT_PATH");
        //文件存储的根路径
        String rootPath = "ATTACH_ROOT_PATH";

       // String attachPreviewPath = rootPath + attachFile.getAttachAddr();
        String attachPreviewPath = rootPath +  "attachAdd";

        try {
            FileInputStream fis = new FileInputStream(attachPreviewPath); // 以byte流的方式打开文件 d:\1.gif
            int i = fis.available(); //得到文件大小
            byte data[] = new byte[i];
            fis.read(data);  //读数据
            response.setContentType("multipart/form-data");
            //response.setContentType("image/*"); //设置返回的文件类型
            OutputStream toClient = response.getOutputStream(); //得到向客户端输出二进制数据的对象
            toClient.write(data);  //输出数据
            toClient.flush();
            toClient.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("图片不存在");
        }
    }


}
